package com.nancal.activiti.controller;

import com.github.pagehelper.Page;
import com.nancal.activiti.entity.Response;
import com.nancal.activiti.entity.pojo.ProcessGroup;
import com.nancal.activiti.service.GroupService;
import com.nancal.common.core.controller.BaseController;
import com.nancal.common.core.page.TableDataInfo;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.GroupQuery;
import org.activiti.engine.identity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @Author TanXInshi
 * @Date 2020/10/14 10:07
 * @Version v1.0
 * @Description 组，控制层
 */

@Slf4j
@RestController
@RequestMapping("/group")
public class ProcessGroupController extends BaseController {
    @Autowired
    private IdentityService identityService;
    @Autowired
    private GroupService groupService;


    @RequestMapping("/updateGroup")
    public Response updateGroup(String id) {
        groupService.updateGroup(id);
        return Response.success();
    }

    /**
     * 分页查询
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list( @RequestBody HashMap<String, String> pageQuery) {
        String pageNum = pageQuery.get("pageNum");
        String pageSize = pageQuery.get("pageSize");
        System.out.println("pageNum"+"pageSize");
        //UserQuery userQuery = identityService.createUserQuery();
        GroupQuery groupQuery = identityService.createGroupQuery();
        Integer pageNum1 = Integer.parseInt(pageNum);
        Integer pageSize1 = Integer.parseInt(pageSize);
        // List<User> userList = userQuery.listPage((pageNum1 - 1) * pageSize1, pageSize1);\
        List<Group> groupList = groupQuery.listPage((pageNum1 - 1) * pageSize1, pageSize1);
        Page<ProcessGroup> list = new Page<>();
        list.setTotal(groupQuery.count());
        list.setPageNum(pageNum1);
        list.setPageSize(pageSize1);
        for (Group group : groupList) {
            ProcessGroup processGroup = new ProcessGroup();
            processGroup.setName(group.getName());
            processGroup.setType(group.getType());
            // TODO: 2020/10/21 用户对应角色，一对多 还是一对一
            list.add(processGroup);
        }
        return getDataTable(list);
    }

    //添加组
    @PostMapping("/addGroup")
    public Response addGroup(@RequestBody Map<String, Object> map) {
        //identityService自带创建组（参数是前端传来的组类）
        Random random = new Random();
        int ran = random.nextInt(10000);
        String s = String.valueOf(ran);

        String name = (String) map.get("name");
        List type = (List) map.get("type");
        String typeString = "";
        for (Object o : type) {
            typeString = typeString + o + "、";
        }

        String substring = typeString.substring(0, typeString.length() - 1);
        //String typeString = JSON.toJSONString(type);


        try {
            Group group = identityService.newGroup(s);
            group.setName(name);
            group.setType(substring);
            identityService.saveGroup(group);
            return Response.success();
        } catch (Exception e) {
            return Response.failure("添加失败，请检查格式是否正确");
        }
    }


    //解除 组——用户 关系   并     删除组
    @RequestMapping("/delGroup")
    public Response delGroup(@RequestBody ArrayList<ProcessGroup> processGroups) {
        try {
            for (int i = 0; i < processGroups.size(); i++) {
                List<User> userList = identityService.createUserQuery().memberOfGroup(processGroups.get(i).getId()).list();
                if (userList != null) {
                    for (User user : userList) {
                        String id = user.getId();
                        identityService.deleteMembership(id, processGroups.get(i).getId());
                    }
                }
                identityService.deleteGroup(processGroups.get(i).getId());
            }
            return Response.success();
        } catch (Exception e) {
            return Response.failure("解除失败,请联系管理员");
        }
    }
}
